package com.wj.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author wen.jie
 * @date 2021/8/26 15:21
 * 赫夫曼树
 */
public class HuffmanTree {

    private Node root;

    public HuffmanTree(int[] arr){
        List<Node> nodes = new ArrayList<>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size()>1) {
            //排序所有元素
            Collections.sort(nodes);
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        root = nodes.get(0);
    }

    /**
     * @author wen.jie
     * @date 2021/8/26 15:39
     * 前序遍历
     */
    public void preOrder() {
        if(root == null) return;
        root.preOrder();
    }

    private class Node implements Comparable<Node>{
        //节点权值
        int value;
        Node left;
        Node right;

        public Node(int value){
            this.value = value;
        }

        @Override
        public int compareTo(Node o) {
            //表示从小到大排序
            return this.value - o.value;
        }

        void preOrder() {
            System.out.println(toString());
            if(this.left != null){
                this.left.preOrder();
            }
            if(this.right != null){
                this.right.preOrder();
            }
        }

        @Override
        public String toString() {
            return "Node{" +
                    "value=" + value +
                    '}';
        }
    }
}
